<template>
	<el-dialog v-model="_d.visible" draggable :close-on-click-modal="false" width="600px">
		<template #header>
			<div style="color: #fff">{{_d.record ? '编辑' : '添加'}}预算</div>
		</template>
	  <el-form class="form-box" :model="_d.form" :rules="_d.rules" ref="formRef" label-width="auto">
			<el-form-item label="预算名称" prop="name">
				<el-input v-model="_d.form.name" placeholder="请输入预算名称" clearable />
			</el-form-item>
			<el-form-item label="预算金额" prop="appliedAmount">
				<el-input-number style="width: 100%;" v-model="_d.form.appliedAmount" :min="0" placeholder="请输入" clearable />
			</el-form-item>
			<el-form-item label="公共预算" prop="isPublicBudget">
				<el-radio-group v-model="_d.form.isPublicBudget">
		      <el-radio :label="true">是</el-radio>
		      <el-radio :label="false">否</el-radio>
		    </el-radio-group>
			</el-form-item>
			<el-form-item label="预算年度" prop="year">
				<el-select style="width: 100%;" v-model="_d.form.year" placeholder="请选择预算年度">
					<el-option v-for="(item, index) in _d.budgetyear" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="预算描述" prop="description">
				<el-input v-model="_d.form.description" type="textarea" placeholder="请输入预算描述" clearable />
			</el-form-item>
			<el-form-item label="预算使用截止期限" prop="deadLine">
				<el-date-picker
	        v-model="_d.form.deadLine"
	        type="date"
	        placeholder="请选择"
	        value-format="YYYY-MM-DD"/>
			</el-form-item>
			<el-form-item label="会议纪要" prop="budgetFileId">
				<div class="w-full">
					<el-button size="small" @click="uploadFile()">上传</el-button>
					<div v-if="_d.fileData" class="file-box">
						<el-icon><Document /></el-icon>
						<span class="name" @click="showFile(_d.fileData)">{{_d.fileData.fileName + _d.fileData.suffix}}</span>
					</div>
				</div>
			</el-form-item>
			<template v-if="userType == 12">
				<el-form-item label="批复总额" prop="approvedAmount">
					<el-input-number style="width: 100%;" v-model="_d.form.approvedAmount" :min="0" placeholder="请输入" clearable />
				</el-form-item>
				<el-form-item label="发布金额" prop="allocatedAmount">
					<el-input-number style="width: 100%;" v-model="_d.form.allocatedAmount" :min="0" placeholder="请输入" clearable />
				</el-form-item>
			</template>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="cancel">关 闭</el-button>
				<el-button :loading="_d.btnLoading" type="primary" @click="save">确 认</el-button>
			</span>
		</template>
	</el-dialog>

	<input v-show="false" ref="fileRef" type="file" @change="fileChange">
</template>

<script lang="ts" setup>
import { reactive, ref, computed, onMounted, watch } from 'vue';
import { ElNotification } from 'element-plus';
import {Document} from '@element-plus/icons-vue'
import {verifyPhone, verifyTelPhone} from "/@/utils/toolsValidate.ts";
import {$get, $post, $postFile} from '/@/utils/request';
import {useUserInfo} from "/@/stores/userInfo.ts";
import {getUserType} from "/@/api/system/user"


const emits = defineEmits(['reload', 'preview']);

const props = defineProps(['userType'])

const oUserInfo = useUserInfo();
const formRef = ref();
const fileRef = ref();

const defalutForm = {
	name: '',
	appliedAmount: 0,
	isPublicBudget: 1,
	year: null,
	description: '',
	approvedAmount: 0,
	allocatedAmount: 0,
	budgetFileId: '', // 附件
	deadLine: '',
}

const _d = reactive({
	visible: false,
	btnLoading: false,

	form: {
		...defalutForm
	},

	rules: {
		name: [
			{ required: true, message: '请填写预算名称', trigger: 'blur' }
		],
		appliedAmount: [
			{ required: true, message: '请填写预算金额', trigger: 'blur' }
		],
		isPublicBudget: [
			{ required: true, message: '请选择是否公共预算', trigger: 'blur' }
		],
		year: [
			{ required: true, message: '请选择预算年度', trigger: 'blur' }
		],
		approvedAmount: [
			{ required: true, message: '请填写批复总额', trigger: 'blur' }
		],
		allocatedAmount: [
			{ required: true, message: '请填写发布金额', trigger: 'blur' }
		],
		deadLine: [
			{ required: true, message: '请选择预算使用截止期限', trigger: 'blur' }
		],
		budgetFileId: [
			{ required: true, message: '请上传会议纪要', trigger: 'blur' }
		],
	},

	// 预算年度
	budgetyear: [],

	fileData: null,
});

watch(() => _d.form.budgetFileId, () => {
	getFile(_d.form.budgetFileId)
})

onMounted(() => {
	$Dict.get('budgetyear').then(res => {
		_d.budgetyear = res;
	})
});

// 打开弹窗
const open = (row) => {
	_d.row = row;

	setTimeout(() => {
		if(!row) {
			Object.assign(_d.form, defalutForm);
		} else {
			for(let key in _d.form) {
				_d.form[key] = row[key];
			}
			_d.form.budgetFileId = row.fileId || '';
		}
		formRef.value.clearValidate();
	}, 30);
		

	_d.visible = true;
};

// 取消
const cancel = () => {
	_d.visible = false;
};

// 保存
const save = () => {
	formRef.value.validate(async (valid) => {
		if (!valid) return;
		if(!_d.row) {
			addData();
		} else {
			editData();
		}
	})
}

const addData = () => {
	let params = {
		..._d.form
	}
	_d.btnLoading = true;
	$post('/budgetSrv/insbudget', params).then(res => {
		if(res.code == 200) {
			ElNotification({
		    title: '提示',
		    message: '添加成功',
		    type: 'success',
		  })
			emits('reload');
			_d.visible = false;
		}
	}).finally(() => {
		_d.btnLoading = false;
	})
}

const editData = () => {
	let params = {
		id: _d.row.id,
		..._d.form
	}
	_d.btnLoading = true;
	$post('/budgetSrv/modifybudget', params).then(res => {
		if(res.code == 200) {
			ElNotification({
		    title: '提示',
		    message: '编辑成功',
		    type: 'success',
		  })
			emits('reload');
			_d.visible = false;
		}
	}).finally(() => {
		_d.btnLoading = false;
	})
}


// 上传附件
function uploadFile() {
	fileRef.value.click();
}
// 上传附件改变
function fileChange(e) {
	let files = e.target.files;
	if(!files.length) {
		return;
	}
	let file = files[0];
	let fd = new FormData();
  fd.append("file", file);
  $postFile(`/budgetSrv/uploadbudgetfile`, fd).then(res => {
  	if(res.code == 200) {
  		ElNotification({
		    title: '提示',
		    message: '上传成功',
		    type: 'success',
		  })
		  _d.form.budgetFileId = res.result.id;
  	}
  }).finally(() => {
  	e.target.value = '';
  })
}

// 获取附件
function getFile(id) {
	if(!id) {
		_d.fileData = null;
		return;
	}
	$get(`/budgetSrv/geibudgetfile/${id}`).then(res => {
		_d.fileData = res.result;
	})
}

function showFile(obj) {
	emits('preview', obj.url)
}


// 导出对象
defineExpose({ open });

</script>
<style lang="scss" scoped>
.form-box {
	min-height: 350px;
}
.budget-ipt {
	:deep(.el-input__inner) {
		text-align: left;
	}
}
.file-box {
	margin-top: 10px;
	background: #F5F7FA;
	display: flex;
	align-items: center;
	padding: 2px 5px;
	color: #999;
	.name {
		margin-left: 10px;
		color: var(--el-color-primary);
		cursor: pointer;
	}
}
</style>
